import os
from PyPDF2 import PdfMerger
from werkzeug.utils import secure_filename
import time
import tempfile

class PDFMerger:
    def __init__(self):
        self.temp_files = []

    def merge(self, files, output_filename='merged.pdf'):
        """
        PDF合并核心功能
        :param files: 上传的文件列表
        :param output_filename: 输出文件名
        :return: 合并后的文件路径
        """
        # 创建输出目录
        output_dir = os.path.join(os.getcwd(), 'output')
        os.makedirs(output_dir, exist_ok=True)
        
        merger = PdfMerger()
        
        try:
            # 处理上传文件
            for file in files:
                filename = secure_filename(file.filename)
                temp_path = os.path.join(tempfile.mkdtemp(), f"temp_{filename}")
                
                # 使用二进制流处理，避免文件锁定
                with open(temp_path, 'wb') as temp_file:
                    file.save(temp_file)
                    self.temp_files.append(temp_path)
                
                # 使用新的文件句柄读取
                with open(temp_path, 'rb') as input_file:
                    merger.append(input_file)

            # 生成输出路径
            output_path = os.path.join(output_dir, output_filename)
            merger.write(output_path)
            return output_path
        finally:
            merger.close()

    def cleanup(self):
        """清理临时文件（带重试机制）"""
        for f in self.temp_files:
            max_retries = 3
            for attempt in range(max_retries):
                try:
                    if os.path.exists(f):
                        os.remove(f)
                    break
                except Exception as e:
                    if attempt < max_retries - 1:
                        time.sleep(0.2 * (attempt + 1))  # 递增等待时间
                    else:
                        print(f"❌ 最终无法删除文件 {f}: {str(e)}") 